package com.film.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.film.common.util.DataTimeUtil;
import com.film.dao.UserMapper;
import com.film.pojo.User;
import com.film.pojo.dto.LoginDto;
import com.film.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    /**
     * 用户
     */
    @Autowired
   private UserMapper userMapper;

    /**
     * 密码验证
     */
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户登录
     * @param dto
     * @return
     * @throws Exception
     */
   @Override
    public User login(LoginDto dto) throws Exception {
       //基于查询的对象封装操作
       QueryWrapper<User> wrapper =new QueryWrapper<>();
       wrapper.in("username",dto.getUsername());
       User user = userMapper.selectOne(wrapper);
       //判断用户名是否为空
       if (user == null) {
           throw new Exception("用户名或密码错误");
       }
       if (!bCryptPasswordEncoder.matches(dto.getPassword(), user.getPassword())){
           throw new Exception("用户名或密码错误");
       }
        return user;
    }

    /**
     * 查找全部用户
     * @return
     */
    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    /**
     * 基于id查找用户
     * @param id
     * @return
     */
    @Override
    public User findById(String id) {
        return userMapper.selectById(id);
    }

    /**
     * 用户更新
     * @param user
     * @return
     */
    @Override
    public User update(User user) {
        return userMapper.selectById(user);
    }

    /**
     * 新增用户
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public User save(User user) throws Exception {
        //判断用户名是否为空
        if (findByUsername(user.getUsername()) != null){
            throw new Exception("用户名已注册");
        }
        //新建用户的时间规范
        String now = DataTimeUtil.getNowTimeString();
        user.setId(UUID.randomUUID().toString());
        user.setCreateAt(now);//插入时间
        user.setUpdateAt(now);//更新时间
        //bCryptPasswordEncoder 加密策略
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return user;
    }

    /**
     * 基于用户名查找
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 基于id删除用户
     * @param id
     */
    @Override
    public void deleteById(String id) {
        userMapper.deleteById(id);
    }
}
